package com.example.ffepeg.async;

import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.*;

@Service
public class AiTestV {
    private static final Map<String, CompletableFuture<String>> tasks = new ConcurrentHashMap<>();
    private static final ExecutorService executor11 = Executors.newFixedThreadPool(2);

    public String startTask() {
        // 生成唯一的任务ID
        String taskId = UUID.randomUUID().toString().replace("-","");
        // 创建一个CompletableFuture来表示这个异步任务
        CompletableFuture<String> future = new CompletableFuture<>();
        tasks.put(taskId, future);
        // 提交任务到线程池执行
        executor11.submit(() -> {
            try {
                // 模拟耗时操作
                Thread.sleep(15000);
                // 完成任务并设置结果
                future.complete("Result for " + taskId);
            } catch (InterruptedException e) {
                future.completeExceptionally(e);
            }
        });
        return taskId;
    }

    public static CompletableFuture<String> getTaskFuture(String taskId) {
        return tasks.get(taskId);
    }

    public void shutdown() {
        executor11.shutdown();
        try {
            if (!executor11.awaitTermination(60, TimeUnit.SECONDS)) {
                executor11.shutdownNow();
            }
        } catch (InterruptedException e) {
            executor11.shutdownNow();
        }
    }


    public String getTaskResult(String taskId) {
        String taskResult = "";
        CompletableFuture<String> taskFuture = getTaskFuture(taskId);
        try {
            taskResult = taskFuture.join();
            System.err.println("获取结果: "+taskResult);
        } catch (CompletionException e) {
            System.err.println("获取结果失败: " + e.getCause().getMessage());
            throw new RuntimeException(e.getCause());
        } finally {
            shutdown();
        }
        return taskResult;
    }


}
